// ✅ 修改：引入 API 服务
import strHtml from "./CommunityPage.html";
import { DomUtils } from "../../utils/DomUtils";
import { communityService } from "../../services/communityService"; // ✅ 新增
import { getCurrentUser } from "../../services/userService";

export class CommunityPage {
  constructor() {
    this.dom = null;
    this.posts = []; // ✅ 修改：初始化为空，等待接口获取
    this.editingPostId = null; // ✅ 新增：用于记录正在编辑的 postId
    this.currentUser = null; // 初始为空
  }

  async render() {
    this.dom = DomUtils.convertToDom(strHtml);
    await this._loadCurrentUser(); // ✅ 新增
    await this._loadData(); // ✅ 修改：替代静态渲染
    this._bindEvents();
    return this.dom;
  }

  async _loadCurrentUser() {
    try {
      const user = await getCurrentUser();
      this.currentUser = {
        name: user.realName || user.username,
        avatar: user.avatar,
        userId: user.id, // ✅ 用后端返回的 userId
      };
    } catch (err) {
      console.error("获取用户失败：", err);
      alert("获取用户信息失败，请重新登录！");
    }
  }

  // ✅ 新增：统一格式的 _loadData 方法
  async _loadData() {
    try {
      const res = await communityService.getAllPosts();
      this.posts = res.data || res || [];
      // 获取每个帖子的评论数
      for (let post of this.posts) {
        const commentCountRes = await communityService.getCommentCount(
          post.postId
        );
        post.commentCount = commentCountRes.data || commentCountRes || 0;
      }
      this._renderPosts(); // 保留原卡片渲染逻辑
    } catch (err) {
      console.error("加载帖子失败", err);
      alert("加载帖子失败，请稍后再试！");
      this.posts = [];
    }
  }

  _renderPosts() {
    const container = this.dom.querySelector("#post-list");
    container.innerHTML = "";

    this.posts.forEach((post, index) => {
      console.log("Post User ID: ", post.userId); // 打印帖子中 userId
      console.log("Current User ID: ", this.currentUser.userId); // 打印当前用户的 userId
      const col = document.createElement("div");
      col.className = "col-md-6 mb-4";

      let truncatedContent = post.content;
      const truncatedLength = 70;
      let words = truncatedContent.split("");
      if (words.length > truncatedLength) {
        truncatedContent = words.slice(0, truncatedLength).join("") + "...";
      }

      // 判断是否是当前用户发布的帖子
      const showEditDeleteButton =
        post.userId === this.currentUser.userId
          ? `
        <div class="edit-delete-icons">
          <i class="fas fa-edit" id="edit-btn-${index}" style="cursor: pointer;"></i>
          <i class="fas fa-trash" id="delete-btn-${index}" style="cursor: pointer;"></i>
        </div>
      `
          : "";

      // 处理图片显示
      let imageHtml = "";
      if (post.imageUrl) {
        // 检查是否是 Base64 格式
        if (post.imageUrl.startsWith("data:image")) {
          imageHtml = `<img src="${post.imageUrl}" class="img-fluid rounded mb-2">`;
        } else {
          // 如果是 BLOB 数据，需要添加 data:image/jpeg;base64, 前缀
          imageHtml = `<img src="data:image/jpeg;base64,${post.imageUrl}" class="img-fluid rounded mb-2">`;
        }
      }

      col.innerHTML = `
        <div class="card p-3 h-100 shadow-sm">
          <div class="d-flex justify-content-between align-items-center mb-2">
            <div class="d-flex align-items-center">
              ${
                post.user
                  ? `
                <img src="${
                  post.user.avatar
                    ? "data:image/jpeg;base64," + post.user.avatar
                    : "assets/images/user-10.jpg"
                }" class="rounded-circle me-2" style="width: 40px; height: 40px;">
                <strong>${post.user.username}</strong>
              `
                  : `<span>用户信息缺失</span>`
              }
            </div>
            ${showEditDeleteButton}
          </div>
          <h5 class="mb-2">${post.title}</h5>
          <p class="truncate-content">${truncatedContent}</p>
          ${imageHtml}
          <div class="d-flex justify-content-between align-items-center text-muted">
            <div>💬 评论 ${post.commentCount || 0}</div>
            <div class="small">${this._formatTime(post.createTime)}</div>
          </div>
        </div>
      `;

      const card = col.querySelector(".card");
      card.addEventListener("click", () => {
        localStorage.setItem("selectedPost", JSON.stringify(post));
        location.hash = "#/post-detail";
      });

      // 绑定编辑按钮事件
      const editBtn = col.querySelector(`#edit-btn-${index}`);
      if (editBtn) {
        editBtn.addEventListener("click", (e) => {
          e.stopPropagation();
          this.editPost(index); // 调用 editPost
        });
      }

      // 绑定删除按钮事件
      const deleteBtn = col.querySelector(`#delete-btn-${index}`);
      if (deleteBtn) {
        deleteBtn.addEventListener("click", (e) => {
          e.stopPropagation();
          this.deletePost(index); // 调用 deletePost
        });
      }

      container.appendChild(col);
    });
  }

  // 编辑帖子
  editPost(index) {
    const post = this.posts[index];
    this.editingPostId = post.postId; // 新增：记录正在编辑的 postId
    this.dom.querySelector("#post-title").value = post.title;
    this.dom.querySelector("#post-content").value = post.content;
    this.dom.querySelector("#post-modal").classList.remove("d-none");

    const modalTitle = this.dom.querySelector("#post-modal h5");
    if (modalTitle) modalTitle.innerText = "修改帖子";

    const submitBtn = this.dom.querySelector("#submit-post");
    submitBtn.innerText = "更新";

    submitBtn.replaceWith(submitBtn.cloneNode(true)); // 克隆按钮重新绑定事件
    const newSubmitBtn = this.dom.querySelector("#submit-post");

    // 修改：处理图片的上传或预览
    const imagePreview = this.dom.querySelector("#image-preview"); // 新增：显示预览图

    newSubmitBtn.onclick = async (event) => {
      event.preventDefault();

      const title = this.dom.querySelector("#post-title").value.trim();
      const content = this.dom.querySelector("#post-content").value.trim();
      const imageInput = this.dom.querySelector("#post-image");

      // 处理图片文件
      let imageUrl = post.imageUrl; // 默认使用原图
      if (imageInput.files.length > 0) {
        const file = imageInput.files[0];
        imageUrl = await this._convertImageToBase64(file);
      }

      const postData = {
        title,
        content,
        imageUrl: imageUrl,
        userId: this.currentUser.userId,
      };

      try {
        await communityService.updatePost(this.editingPostId, postData);
        this.editingPostId = null;
        this.dom.querySelector("#post-modal").classList.add("d-none");
        await this._loadData(); // 刷新帖子列表
      } catch (err) {
        console.error("更新失败", err);
        alert("更新失败，请稍后再试！");
      }
    };
  }

  // 新增：将图片转换为 Base64
  _convertImageToBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => resolve(reader.result);
      reader.onerror = reject;
      reader.readAsDataURL(file);
    });
  }

  // 删除帖子
  async deletePost(index) {
    const post = this.posts[index];
    if (!confirm("确定删除该帖子？")) return;

    try {
      await communityService.deletePost(post.postId);
      await this._loadData();
    } catch (err) {
      console.error("删除失败", err);
      alert("删除失败，请稍后再试！");
    }
  }

  _formatTime(date) {
    const diff = Math.floor((Date.now() - new Date(date)) / 1000);
    if (diff < 60) return "刚刚";
    if (diff < 3600) return `${Math.floor(diff / 60)} 分钟前`;
    if (diff < 86400) return `${Math.floor(diff / 3600)} 小时前`;
    const d = new Date(date);
    return `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;
  }

  // 绑定事件
  _bindEvents() {
    const modal = this.dom.querySelector("#post-modal");
    const showBtn = this.dom.querySelector("#create-post-btn");
    const cancelBtn = this.dom.querySelector("#cancel-post");
    const submitBtn = this.dom.querySelector("#submit-post");

    // 点击新增按钮时重置弹窗内容
    showBtn.addEventListener("click", () => {
      // 清空输入框
      this.dom.querySelector("#post-title").value = "";
      this.dom.querySelector("#post-content").value = "";

      // 重置图片预览
      const imagePreview = this.dom.querySelector("#image-preview");
      imagePreview.src = ""; // 清空图片预览

      // 设置弹窗标题为 "新增帖子"
      const modalTitle = this.dom.querySelector("#post-modal h5");
      if (modalTitle) modalTitle.innerText = "新增帖子";

      // 设置提交按钮文字为 "发布"
      submitBtn.innerText = "发布";

      // 重置编辑状态
      this.editingPostId = null;
      modal.classList.remove("d-none");
    });

    cancelBtn.addEventListener("click", () => {
      modal.classList.add("d-none");
      this.editingPostId = null;
    });

    submitBtn.addEventListener("click", async () => {
      const title = this.dom.querySelector("#post-title").value.trim();
      const content = this.dom.querySelector("#post-content").value.trim();
      const imageInput = this.dom.querySelector("#post-image");

      if (!title || !content) return alert("请填写标题和内容");

      let imageUrl = "";
      if (imageInput.files.length > 0) {
        imageUrl = await this._convertImageToBase64(imageInput.files[0]);
      }

      const postData = {
        title,
        content,
        imageUrl: imageUrl,
        userId: this.currentUser.userId,
      };

      try {
        if (this.editingPostId) {
          // 更新帖子
          await communityService.updatePost(this.editingPostId, postData);
        } else {
          // 新增帖子
          await communityService.createPost(postData);
        }
        modal.classList.add("d-none");
        await this._loadData(); // 刷新帖子列表
      } catch (err) {
        console.error("发布失败", err);
        alert("发布失败，请稍后再试！");
      }
    });
  }
}
